package cn.elane.kibana.demo.global.util;

import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Key;

/**
 * @author Chenyu
 */
public class DesUtil {

	/**
	 * 向量
	 */
	private final static String IV = "0102030405060708";

	private final static String KEY = "C5C5AF0C419445C16D214638358AB0C9FA7F36B1DEAEDF8D";

	/**
	 * 加解密统一使用的编码方式
	 */
	private final static Charset UTF8 = StandardCharsets.UTF_8;


	/**
	 * 3DES加密
	 *
	 * @param plainText 源文本
	 * @return 加密文本
	 */
	public static String encode(String plainText) {
		try {
			Key deskey = null;
//			DESedeKeySpec spec = new DESedeKeySpec(KEY.getBytes());
//			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESEde");

			deskey = SecretKeyFactory.getInstance("DESede").generateSecret(new DESedeKeySpec(KEY.getBytes()));
			Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
			byte[] iv1 = IV.getBytes(UTF8);
			byte[] ivBuffer = new byte[8];
			System.arraycopy(iv1, 0, ivBuffer, 0, 8);
			IvParameterSpec ips = new IvParameterSpec(ivBuffer);
			cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
			byte[] encryptData = cipher.doFinal(plainText.getBytes(UTF8));
			return Base64Utils.encodeToString(encryptData);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return plainText;
	}

	/**
	 * 3DES解密
	 *
	 * @param encryptText 加密文本
	 * @return 源文本
	 */
	public static String decode(String encryptText) {
		try {
			Key desKey = null;
			DESedeKeySpec spec = new DESedeKeySpec(KEY.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
			desKey = keyFactory.generateSecret(spec);
			Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
			byte[] iv1 = IV.getBytes(UTF8);
			byte[] ivBuffer = new byte[8];
			System.arraycopy(iv1, 0, ivBuffer, 0, ivBuffer.length);
			IvParameterSpec ips = new IvParameterSpec(ivBuffer);
			cipher.init(Cipher.DECRYPT_MODE, desKey, ips);

			byte[] decryptData = cipher.doFinal(Base64Utils.decodeFromString(encryptText));
			return new String(decryptData, UTF8);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptText;
	}


	public static void main(String[] args) {
//		String text = "321\r\nwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww";
		String text = "\ninsert into test(uuid,name) \n" +
				"values(\n" +
				"{req: true, xql:\"'$uuid$', '$name$'\"}\n" +
				")";
		System.err.println(System.currentTimeMillis());
		String encodeData = encode(text);
		System.err.println(System.currentTimeMillis());
		String decodeData = decode(encodeData);
		System.out.println("原始字符串：" + text);
		System.out.println("加密后的值：" + encodeData);
		System.out.println("解密后的值：" + decodeData);
	}

}
